package cn.coco.jf.fw.admin.config;

import java.io.File;
import java.util.UUID;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.json.IJsonFactory;
import com.jfinal.json.Json;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSource;
import com.jfinal.template.source.FileSource;
import com.jfinal.template.source.ISource;
import com.jfinal.upload.OreillyCos;
import com.oreilly.servlet.multipart.FileRenamePolicy;

import cn.coco.jf.fw.admin.cache.SysCacheManager;
import cn.coco.jf.fw.admin.config.consts.SysConfigConst;
import cn.coco.jf.fw.admin.config.consts.SysConsts;
import cn.coco.jf.fw.admin.sys.controller.login.LoginController;
import cn.coco.jf.fw.admin.sys.controller.ssoAuth.SSOAuthController;
import cn.coco.jf.fw.admin.util.TplUtil;
import cn.coco.jf.fw.core.config.Mapping;
import cn.coco.jf.fw.core.db.SysGenCdkeyTbl;
import cn.coco.jf.fw.core.db.SysGuideTbl;
import cn.coco.jf.fw.core.db.SysMenuRoleRel;
import cn.coco.jf.fw.core.db.SysMenuTbl;
import cn.coco.jf.fw.core.db.SysPtnVerbTbl;
import cn.coco.jf.fw.core.db.SysRoleTbl;
import cn.coco.jf.fw.core.db.SysThirdUserTbl;
import cn.coco.jf.fw.core.db.SysUserOptLogTbl;
import cn.coco.jf.fw.core.db.SysUserTbl;
import cn.exlu.coco.core.utils.DateUtil;

public abstract class JkwebAdminConfig extends JFinalConfig{

    /**
     * 常量值设置
     */
    @Override
    public void configConstant(Constants me) {
    	
    	me.setJsonFactory(new IJsonFactory() {
	        public Json getJson() { return new JkwebJson();}});
        me.setEncoding("utf-8");
        me.setError404View("/404.html");
        me.setError500View("/500.html");
        me.setErrorView(SysConsts.RENDER_ERR_601_NO_AUTH, "/601NoAuth.html");
        
//        me.setMaxPostSize(1024 * 1024 * 1024 * 1);
        
        // 设置开发模式
        me.setDevMode(SysConfigConst.CONFIG_DEV_MODE);
        // 设置上传路径
        me.setBaseUploadPath(SysConfigConst.CONFIG_BASE_UPLOAD_PATH);
        
        OreillyCos.setFileRenamePolicy(new FileRenamePolicy(){

            @Override
            public File rename(File f) {
                if(f == null){
                    return null;
                }
                String srcFileName = f.getName();
                String descFileName = UUID.randomUUID()+DateUtil.currentDateTimestamp()+srcFileName.substring(srcFileName.lastIndexOf("."));
                File newFile = new File(f.getParentFile(), descFileName);
                f.renameTo(newFile);
                return newFile;
            }
        });

    }

    Engine me;
    /**
     * 模板引擎设置
     */
    @Override
    public final void configEngine(Engine me) {
        // 设置开发模式，防止页面缓存
        me.setDevMode(SysConfigConst.CONFIG_DEV_MODE);
        me.addSharedFunction("WEB-INF/common/header.tpl");
        
        me.addSharedObject("TplUtil", new TplUtil());
        
        this.me = me;
        
        sharedObject();

    }
    
    protected void addSharedObject(String name, Object object) {
        me.addSharedObject(name, object);
    }

    @Override
    public final void configHandler(Handlers me) {
        // 设置请求过滤
//        me.add(new UrlSkipHandler(".*\\.html", false));

    	me.add(new GlobalViewHandler());

    }

    /**
     * 全局拦截器
     */
    @Override
    public final void configInterceptor(Interceptors me) {
    	me.add(new SessionInViewInterceptor());
    }

    String baseSqlTemplateStream = "/cn/coco/jf";
    String baseSqlTemplatePath = PathKit.getRootClassPath()+baseSqlTemplateStream;
    
    @Override
    public final void configPlugin(Plugins me) {
        // 数据源配置
        DruidPlugin druidMysql = new DruidPlugin(SysConfigConst.DB_URL, SysConfigConst.DB_USERNAME, SysConfigConst.DB_PASSWD);
        druidMysql.setDriverClass(SysConfigConst.DB_DRIVER);
//        druidMysql.setDriverClass("com.mysql.jdbc.Driver");
        druidMysql.set(SysConfigConst.DB_INITIALSIZE, SysConfigConst.DB_MINIDLE, SysConfigConst.DB_MAXACTIVE);
        me.add(druidMysql);
        arp = new ActiveRecordPlugin(SysConsts.DATA_SOURCE_NAME_MYSQL, druidMysql);

        arp.setBaseSqlTemplatePath(baseSqlTemplatePath);

        // ======系统======
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/index.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/guide.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/login.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/user.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/role.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/sys.sql"));
        arp.addSqlTemplate(new ClassPathSource(baseSqlTemplateStream, "sys/sql/ptn.sql"));
        
        sqlTemplate();

        Mapping mapping = new Mapping(arp);
        arp.addMapping("sys_gen_cdkey_tbl", "cdkeyPtn", SysGenCdkeyTbl.class);
        arp.addMapping("sys_menu_tbl", "id", SysMenuTbl.class);
        arp.addMapping("sys_user_tbl", "USER_CODE", SysUserTbl.class);
        arp.addMapping("sys_guide_tbl", "id", SysGuideTbl.class);
        arp.addMapping("sys_user_opt_log_tbl", "id", SysUserOptLogTbl.class);
        arp.addMapping("sys_role_tbl", "roleId", SysRoleTbl.class);
        arp.addMapping("sys_menu_role_rel", "id", SysMenuRoleRel.class);
        arp.addMapping("sys_ptn_verb_tbl", "ptnId", SysPtnVerbTbl.class);
        arp.addMapping("sys_third_user_tbl", "authType,userCodeThird", SysThirdUserTbl.class);
        
        db(mapping);

        arp.setDialect(new MysqlDialect());
        arp.setDevMode(SysConfigConst.CONFIG_DEV_MODE);
        arp.setShowSql(SysConfigConst.CONFIG_DEV_MODE);

        me.add(arp);

    }
    ActiveRecordPlugin arp;
    AdminRoutes routes;
    protected void addSqlTemplate(String sqlTemplate){
        arp.addSqlTemplate(new FileSource(baseSqlTemplatePath, sqlTemplate));
    }
    
    protected void addSqlTemplate(ISource sqlTemplate) {
        arp.addSqlTemplate(sqlTemplate);
    }

    protected void addController(String controllerKey, Class<? extends Controller> controllerClass, String viewPath){
        routes.add(controllerKey, controllerClass, viewPath);
    }
    
    public abstract void sqlTemplate();

    public abstract void db(Mapping mapping);
    
    public abstract void controller();
    
    public void sharedObject() {
        
    }


    /**
     * 设置访问路由
     */
    @Override
    public final void configRoute(Routes me) {
        routes = new AdminRoutes();
        routes.configBefore();
        
        controller();
        
        routes.configAfter();
        
        me.add(routes);

        me.setBaseViewPath(SysConsts.BASE_VIEW_PATH);
        
        me.add("/login", LoginController.class, "/");
        me.add("/ssoAuth", SSOAuthController.class, "/");
    }

    @Override
    public final void onStart() {
        super.onStart();
        SysCacheManager.start();
    }

    @Override
    public final void onStop() {
        super.onStop();
        SysCacheManager.terminal();
    }
    
    
    

}
